package com.warthur.vertx.demo.handler;

import com.warthur.vertx.demo.common.enums.Bean;
import com.warthur.vertx.demo.common.utils.ResponseUtils;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.asyncsql.AsyncSQLClient;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.web.RoutingContext;
import io.vertx.redis.RedisClient;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author warthur
 * @date 2019/10/09
 */
@Slf4j
public class HelloHandler {

    public static void hello(RoutingContext context) {

        context.response().end("hello world");
    }

    public static void handle(RoutingContext event) {

        AsyncSQLClient client = event.vertx().getOrCreateContext().get(Bean.MYSQL_CLIENT.getName());

        client.query("select * from t_user", as -> {
            if (as.succeeded()) {
                ResultSet resultSet = as.result();
                log.info("mysql 成功了");
                ResponseUtils.build(event).success().body(resultSet.getRows());
            } else {
                log.info("mysql 失败了");
            }
        });

    }

    public static void body(RoutingContext event) {

        log.info("接收数据：{}", event.getBodyAsString());

        RedisClient redisClient = event.vertx().getOrCreateContext().get(Bean.REDIS_CLIENT.getName());
        Promise<String> promise = Promise.promise();
        redisClient.get("age", promise);
        promise.future().setHandler(as -> {
            if (as.succeeded()) {

                System.out.println(as.result());
            }
        });

        event.put("response", "Hello World")
                .response().putHeader("version", "v2")
                .end("Hello World from Vert.x-Web!");
    }
}
